import router from '@system.router';
import prompt from '@system.prompt';
//import window from '@ohos.window';
import jsFa from '../../common/utils/jsfa.js';
import Api from '../../common/utils/apis.js'
import Timer from '../../common/utils/timehelper.js'
import Icons from '../../common/utils/starIcons.config.js'

export default {
    data: {
        title: "巨蟹座的一天",
        time: '7月22日,星期四',
        menus: [
            {
                name: '综合运势',
                value: 85
            },
            {
                name: '速配星座',
                value: '水瓶座'
            },
            {
                name: '幸运颜色',
                value: '生态绿'
            },
            {
                name: '幸运数字',
                value: 6
            }
        ],
        today: '巨蟹座今天在公司当中有比较强的上进心，工作当中的问题也会一一找出来，努力解决掉。压力虽然不小，但是也可以转化成相当的动力，督促自己前行。',
        todoList: [
//            {
//                name: '签签雀割',
//                time: '明天',
//                state: '',
//                finishTime: '',
//                transX: 0,
//                startX: 0
//            },
        ],
        showDialog: false,
        dateList: [
            {
                name: '今天',
                icon: '',
                index: 0
            },
            {
                name: '明天',
                icon: '',
                index: 1
            },
            {
                name: '后天',
                icon: '',
                index: 2
            },
            {
                name: '选择日期',
                icon: '/common/images/icons/icons-down2.png',
                activeIcon: '/common/images/icons/icon-down.png',
                index: 3
            }
        ],
        dateIndex: 0,
        textAreaValue: '',
        baseData:[],
        user:{
            ConsCode:'',
            ConsName:'巨蟹座',
            ConsImage:{url:'/common/images/starts/jxz.png',width:'445px',height:'358px',opacity:1},
            ConsDate:''
        },
        ConsBgData:Icons
    },
    onInit() {
        this.getBaseInfo()
        this.getCurrentDate()
        this.updateUserConsImage()
        this.getTasks()
    },
    onAttached() {
        //        const eventType = 'keyboardHeightChange'
        //        window.on(eventType, (err, data) => {
        //            if (err) {
        //                console.error('Failed to enable the listener for keyboard height changes. Cause: ' + JSON.stringify(err));
        //                return;
        //            }
        //            console.info('Succeeded in enabling the listener for keyboard height changes. Data: ' + JSON.stringify(data));
        //        });
    },
//    更新设置当前日期
    getCurrentDate(){
        const Day_Name = ['','星期一','星期二','星期三','星期四','星期五','星期六','星期天']
        const time = new Date()
        const month = time.getMonth()
        const date = time.getDate()
        const day = time.getDay()
        this.time = `${month+1}月${date}日,${Day_Name[day]}`
    },
//    获取用户当前星座，更新用户星座code，星座图片，今日运势数据
    getData() {
        jsFa.GetUserCon().then(res => {
            this.title = `${res}的一天`
            this.user.ConsName = res
            this.updateUserConsImage()
            this.updateUserConsCode()
        }).catch(err => {
            prompt.showToast({
                message: '网络错误，获取用户星座失败' + JSON.stringify(err),
                duration: 30000,
            });
        })
    },
//    获取星座今日运势
    getTodayConsData(){
        Api.getTodayConsFortune({e_Cons:this.user.ConsCode}).then(res => {
//            prompt.showToast({
//                message: '今日运势：' + JSON.stringify(res),
//                duration: 30000,
//            });
            const data = res
            this.menus[0].value = data.all
            this.menus[1].value = data.friend
            this.menus[2].value = data.color
            this.menus[3].value = data.number
            this.today = data.summary

        }).catch(err => {
                prompt.showToast({
                message: '网络错误，获取数据失败 ' + JSON.stringify(err),
                duration: 30000,
            });
        })
    },
//    跳转星座详情页面
    toDetailPage() {
        router.push({
            uri:'pages/detail/detail'
        })
    },
//    更新当前用户星座背景图
    updateUserConsImage(){
        this.user.ConsImage = this.ConsBgData[this.user.ConsName]
    },
//    更新当前用户星座code
    updateUserConsCode(){
        const consMap = {}
        this.baseData.map(item => {
            const start = formatDate(item.startDate.toString())
            const end = formatDate(item.endDate.toString())
            consMap[item.name] = {code:item.code,date:`${start}-${end}`}
        })
        function formatDate(dateString){
            if(dateString.length === 3){
                return `${dateString[0]}月${dateString[1]}${dateString[2]}日`
            }
            if(dateString.length === 4){
                return `${dateString[0]}${dateString[1]}月${dateString[2]}${dateString[3]}日`
            }
        }
//        prompt.showToast({
//            message: '星座日期：' + JSON.stringify(this.baseData[0].startDate.toString().length),
//            duration: 30000,
//        });
        this.user.ConsCode = consMap[this.user.ConsName].code
        this.user.ConsDate = consMap[this.user.ConsName].date

        this.getTodayConsData()
    },
//    获取所有星座基础信息
    getBaseInfo(){
        Api.getConstellations()
            .then(data => {
            this.baseData = data
            this.getData()
            })
            .catch(err => {
                prompt.showToast({
                message: '获取星座基础信息出错啦! ' + JSON.stringify(err),
                duration: 30000,
            });
        });
    },
//    弹出星座选择组件
    handleChooseConst() {
        console.log('星座选择按钮被点击了')
        this.showDialog = true
    },
//    处理星座选择事件
    handleChooseSubmit(e){
//        prompt.showToast({
//            message: '当前选择星座: ' + e.detail.name+'id:'+e.detail.code,
//            duration: 30000,
//        })
        jsFa.UpdateUserCon(e.detail.code).then(res => {
            this.user.ConsCode = e.detail.code
            this.getData()
            this.handleClose()
        }).catch(err => {
                prompt.showToast({
                message: '设置星座失败！' + JSON.stringify(err),
                duration: 30000,
            });
        })
    },
//    关闭星座选择组件
    handleClose() {
        this.showDialog = false
    },
//    获取首页最近五天的任务数据
    getTasks(){
//        prompt.showToast({
//            message: '获取最近五天数据',
//            duration: 30000,
//        });
        jsFa.GetTaskIn5Days().then(res => {
                this.todoList = res.sort((a,b)=>{
                    return a.finish-b.finish;
                }).map(item => {
                    return {
                        id:item.id,
                        name:item.title,
                        state:item.finish,
                        time:Timer.dateTaskFormat(item.tM),
                        finishTime: Timer.dateTaskFormat(item.tM),
                        transX: 0,
                        startX: 0
                    }
                })
        })
    },
//    跳转任务页面
    toMore() {
        router.push({
            uri: 'pages/tasks/tasks'
        })
    },
//    弹出新建任务组件
    handleCreate() {
        this.$element('createTask').show()
        this.$element('textarea').focus()
    },
//    任务时间选择
    handleTaskDateChoose(idx) {
//        console.log(idx)
        let date = new Date()
        let dateString
        this.dateIndex = idx
        switch (idx) {
            case 0:
            dateString = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
            break;
            case 1:
            dateString = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate() + 1}`;
            break;
            case 2:
            dateString = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate() + 2}`;
            break;
            case 3:
            break;
        }
//        console.log(dateString)
    },
    handleTextAreaBlur(e) {

    },
//    任务内容获取
    handleTextAreaChange(e) {
        this.textAreaValue = e.text
//        prompt.showToast({
//            message: 'value: ' + e.text + ', lines: ' + e.lines + ', height: ' + e.height,
//            duration: 3000,
//        });
    },
//    新建任务
    handleSubmitTask() {
        if (!this.textAreaValue) {
            prompt.showToast({
                message: '请先输入任务内容',
                duration: 3000,
            });
            return
        }
        jsFa.AddTask(this.textAreaValue, this.textAreaValue, "2021-09-30").then(data=>{
            this.getTasks();
        }).catch(err => {
            prompt.showToast({
                message: '添加任务失败：' + JSON.stringify(err),
                duration: 30000,
            });
        });
        this.$element('createTask').close()
        this.textAreaValue = ''
    },
//    删除任务
    handleDeleteTask(e){
        const id = e.detail.item.id
        jsFa.DeleteTask(id).then(res => {
            this.getTasks()
        })
    },
//    任务完成标记
    handleFinishTask(e){
        const id = e.detail.item.id
        jsFa.FinishTask(id).then(res => {
            this.getTasks()
        })
    }
}
